package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class DButils {
    private static String userName;
    private static String password;
    private static String url;
    private static String driverClassName;
    //使用静态代码块初始化数据库连接工具，只在类加载时执行一次，
    static {
        Properties properties = new Properties();
//        InputStream is = ClassLoader.getSystemResourceAsStream("DataSource.properties");
        InputStream is = DButils.class.getResourceAsStream("/DataSource.properties");
//        String dir = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
//        System.out.println(dir);
//        InputStream is = null;
//        try {
//            is = new FileInputStream(dir+"DataSource.properties");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            System.out.println("驱动加载失败");
//        }
        try {
            properties.load(is);
            userName = properties.getProperty("userName");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            driverClassName = properties.getProperty("driverClassName");
            //加载驱动
            Class.forName(driverClassName);
            //关闭流
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("驱动加载失败");
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        connection = DriverManager.getConnection(url,userName,password);
        return connection;
    }

    /**
     * 关闭连接
     * @param connection
     * @param ps
     */
    public  static void close(Connection connection, PreparedStatement ps) {
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null!=ps) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
